/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.expert.service;

import java.util.Arrays;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.service.BaseService;
import com.chlitina.store.common.utils.StringUtils;
import com.chlitina.store.modules.expert.dao.ParameterCategoryDao;
import com.chlitina.store.modules.expert.dao.ParameterDao;
import com.chlitina.store.modules.expert.entity.Parameter;
import com.chlitina.store.modules.expert.entity.ParameterCategory;

/**
 * 参数Service
 * @author lvbo
 * @version 2013-06-05
 */
@Component
@Transactional(readOnly = true)
public class ParameterService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(ParameterService.class);
	
	@Autowired
	private ParameterDao parameterDao;
	
	@Autowired
	private ParameterCategoryDao parameterCategoryDao;
	
	public Parameter get(Long id) {
		return parameterDao.findOne(id);
	}
	
	public List<Parameter> getList(Long category_id) {
		return parameterDao.getList(category_id);
	}
	
	public ParameterCategory getParameterCategory(Long id) {
		return parameterCategoryDao.findOne(id);
	}
	
	public Page<Parameter> find(Page<Parameter> page, Long id, String searchName) {
		DetachedCriteria dc = parameterDao.createDetachedCriteria();
		if (id != null){
			dc.add(Restrictions.eq("parameterCategory.id", id));
		}
		if (StringUtils.isNotEmpty(searchName)){
			dc.add(Restrictions.like("name", "%"+searchName+"%"));
		}
		dc.addOrder(Order.asc("id"));
		return parameterDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Parameter parameter) {
		parameterDao.clear();
		parameterDao.save(parameter);
		parameterCategoryDao.refresh(parameter.getParameterCategory());
	}
	
	public boolean uniqueName(String name) {
		List<Parameter> lists = parameterDao.uniqueName(name);
		return lists ==null || lists.size() == 0;
	}
	
	@Transactional(readOnly = false)
	public void delete(Parameter parameter) {
		parameter.getParameterCategory().getChildList().remove(parameter);
		parameterDao.delete(parameter);
	}
	
	//获取权重和
	public long getSumWeightByIds(Long [] parameterIdArray) {
		return parameterDao.getSumWeightByIds(Arrays.asList(parameterIdArray));
	}
	//获取当前记录排第几位
	public int getIndexById(Long currentId) {
		DetachedCriteria dc = parameterDao.createDetachedCriteria();
		dc.add(Restrictions.le("id", currentId));
		dc.addOrder(Order.asc("id"));
		return (int)parameterDao.count(dc);
	}
}
